﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace copy2smug
{
    class DownloadData
    {
        /// <summary>
        /// Downloads a byte stream from a URL.
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        /// <remarks>Sourced from http://www.vcskicks.com/download_file_http2.php </remarks>
        public static byte[] Download(string url)
        {
            byte[] downloadedData;
            downloadedData = new byte[0];

            try
            {
                //Get a data stream from the url
                WebRequest req = WebRequest.Create(url);
                WebResponse response = req.GetResponse();
                Stream stream = response.GetResponseStream();

                //Download in chuncks
                byte[] buffer = new byte[1024];

                //Get Total Size
                int dataLength = (int)response.ContentLength;

                //Download to memory
                //Note: adjust the streams here to download directly to the hard drive
                MemoryStream memStream = new MemoryStream();
                while (true)
                {
                    //Try to read the data
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        //Finished downloading
                        break;
                    }
                    else
                    {
                        //Write the downloaded data
                        memStream.Write(buffer, 0, bytesRead);
                    }
                }

                //Convert the downloaded stream to a byte array
                downloadedData = memStream.ToArray();

                //Clean up
                stream.Close();
                memStream.Close();
            }
            catch (Exception)
            {
                //May not be connected to the internet
                //Or the URL might not exist
                //MessageBox.Show("There was an error accessing the URL.");
            }

            return downloadedData;
        }
    }
}
